const { createLogger, transports, format } = require('winston');
const Service = require('node-windows').Service;
const path = require('path');

const logger = createLogger({
    level: 'info',
    format: format.json(),
    transports: [
        new transports.Console(),
        new transports.File({ filename: 'service.log' })
    ]
});

logger.info('开始执行 service.js');

const svcPath = path.join(__dirname, 'server.js');
logger.info(`Resolved service script path: ${svcPath}`);

let svc = new Service({
    name: 'autoSendMail',
    description: '插件用本地自动监听发送邮件服务',
    script: svcPath
});

svc.on('install', () => {
    logger.info('服务安装事件已触发');
    svc.start();
});

svc.on('start', () => {
    logger.info('服务启动成功');
});

svc.on('stop', () => {
    logger.info('服务已停止');
});

svc.on('error', (err) => {
    logger.error('服务报错:', err.message || err);
});

logger.info('开始安装服务');
svc.install((err) => {
    if (err) {
        logger.error('服务安装失败:', err);
        return;
    }
    logger.info('服务安装成功');
});